<!--
  智慧社区管理系统 - 维修工单分配弹窗
  @author Wu.Liang
  @date 2025-01-30
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="分配维修工单"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="工单信息">
        <div class="order-info">
          <p><strong>工单号：</strong>{{ repairOrder?.orderNo }}</p>
          <p><strong>维修标题：</strong>{{ repairOrder?.title }}</p>
          <p><strong>维修地址：</strong>{{ repairOrder?.repairAddress }}</p>
        </div>
      </el-form-item>
      
      <el-form-item label="维修人员" prop="repairmanId">
        <el-select
          v-model="formData.repairmanId"
          placeholder="请选择维修人员"
          style="width: 100%"
          filterable
          @change="handleRepairmanChange"
        >
          <el-option
            v-for="item in repairmanList"
            :key="item.id"
            :label="`${item.name} (${item.phone})`"
            :value="item.id"
          >
            <div class="repairman-option">
              <div class="repairman-info">
                <span class="repairman-name">{{ item.name }}</span>
                <span class="repairman-phone">{{ item.phone }}</span>
              </div>
              <div class="repairman-stats">
                <el-tag size="small" type="info">当前工单: {{ item.currentOrders || 0 }}</el-tag>
                <el-tag size="small" type="success">已完成: {{ item.totalCompleted || 0 }}</el-tag>
              </div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入分配备注（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确认分配
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { commonApi } from '@/api/repair'
import type { RepairOrder } from '../types/repair'

// 作者: Wu.Liang

// Props
interface Props {
  modelValue: boolean
  repairOrder: RepairOrder | null
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [data: any]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const repairmanList = ref<any[]>([])

// 表单数据
const formData = reactive({
  repairmanId: undefined as number | undefined,
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  repairmanId: [
    { required: true, message: '请选择维修人员', trigger: 'change' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 生命周期
onMounted(() => {
  // 不在组件挂载时加载数据，而是在弹窗打开时加载
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    resetForm()
    // 弹窗打开时加载维修人员列表
    loadRepairmanList()
  }
})

// 加载维修人员列表
const loadRepairmanList = async () => {
  try {
    const response = await commonApi.getRepairmanList({})
    if (response.code === 200) {
      repairmanList.value = response.data || []
    } else {
      // 如果接口不存在，使用模拟数据
      repairmanList.value = [
        { id: 1, name: '张师傅', phone: '13800138001', currentOrders: 2, totalCompleted: 156 },
        { id: 2, name: '李师傅', phone: '13800138002', currentOrders: 1, totalCompleted: 89 },
        { id: 3, name: '王师傅', phone: '13800138003', currentOrders: 0, totalCompleted: 234 },
        { id: 4, name: '赵师傅', phone: '13800138004', currentOrders: 3, totalCompleted: 67 }
      ]
    }
  } catch (error) {
    console.error('加载维修人员列表失败:', error)
    // 使用模拟数据
    repairmanList.value = [
      { id: 1, name: '张师傅', phone: '13800138001', currentOrders: 2, totalCompleted: 156 },
      { id: 2, name: '李师傅', phone: '13800138002', currentOrders: 1, totalCompleted: 89 },
      { id: 3, name: '王师傅', phone: '13800138003', currentOrders: 0, totalCompleted: 234 },
      { id: 4, name: '赵师傅', phone: '13800138004', currentOrders: 3, totalCompleted: 67 }
    ]
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    repairmanId: undefined,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 维修人员选择变化
const handleRepairmanChange = (repairmanId: number) => {
  const selectedRepairman = repairmanList.value.find(item => item.id === repairmanId)
  if (selectedRepairman) {
    console.log('选择的维修人员:', selectedRepairman)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = {
      repairmanId: formData.repairmanId!,
      remark: formData.remark || undefined
    }
    
    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.order-info {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
  
  p {
    margin: 0 0 8px 0;
    line-height: 1.5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    strong {
      color: #303133;
    }
  }
}

.repairman-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  
  .repairman-info {
    display: flex;
    flex-direction: column;
    
    .repairman-name {
      font-weight: 500;
      color: #303133;
    }
    
    .repairman-phone {
      font-size: 12px;
      color: #909399;
      margin-top: 2px;
    }
  }
  
  .repairman-stats {
    display: flex;
    gap: 4px;
  }
}

.dialog-footer {
  text-align: right;
}
</style> 